package third_components

import (
	"encoding/base64"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"project_api/user_web/utils"
	"regexp"
	"strings"
)

// 直接将 base64 图片上传到阿里云 OSS
func uploadBase64ToOSS(client *oss.Client, bucketName, objectName, base64Data string) error {
	// 获取指定的 Bucket
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return fmt.Errorf("获取 Bucket 失败: %v", err)
	}

	// 去掉 base64 编码中的前缀部分，比如 "data:image/png;base64,"
	if strings.HasPrefix(base64Data, "data:image") {
		base64Data = strings.Split(base64Data, ",")[1]
	}

	// 解码 base64 数据
	data, err := base64.StdEncoding.DecodeString(base64Data)
	if err != nil {
		return fmt.Errorf("base64 解码失败: %v", err)
	}

	// 将解码后的数据上传到 OSS
	err = bucket.PutObject(objectName, strings.NewReader(string(data)))
	if err != nil {
		return fmt.Errorf("上传图片到 OSS 失败: %v", err)
	}

	return nil
}

// UploadBase64Image 处理 base64 数据并上传到 OSS
func UploadBase64Image(accessKeyID, accessKeySecret, endpoint, bucketName, base64Str string, fileType int) (string, error) {
	// 获取文件路径和扩展名
	path, ext, err := processBase64Data(fileType, base64Str)
	if err != nil {
		return "", err
	}

	// 生成 objectName
	objectName := fmt.Sprintf("%s%s.%s", path, utils.GetRandomStr(16, false), ext)

	// 创建 OSS 客户端
	client, err := oss.New(endpoint, accessKeyID, accessKeySecret)
	if err != nil {
		return "", fmt.Errorf("创建 OSS 客户端失败: %v", err)
	}

	// 直接将 base64 数据上传到 OSS
	err = uploadBase64ToOSS(client, bucketName, objectName, base64Str)
	if err != nil {
		return "", err
	}

	// 返回上传后的文件路径（objectName）
	return objectName, nil
}

func main() {
	//// 配置 OSS 信息
	accessKeyID := "LTAI5tQfySTKpDPGw5T82UEG"
	accessKeySecret := "U8dFsM8IFb77BGNbc2I1RSfCE1Sa1t"
	endpoint := "https://oss-cn-qingdao-internal.aliyuncs.com"
	bucketName := "sgyuyin-resource"
	base64Str := ""
	fileType := 1

	// 调用 uploadBase64Image 上传图片并获取 objectName
	objectName, err := UploadBase64Image(accessKeyID, accessKeySecret, endpoint, bucketName, base64Str, fileType)
	if err != nil {
		fmt.Println("上传失败:", err)
		return
	}

	// 输出上传后的文件路径
	fmt.Println("上传成功，文件路径:", objectName)
}

func processBase64Data(file int, base64Data string) (string, string, error) {
	var path string
	var re *regexp.Regexp
	re = regexp.MustCompile(`^data:(\S+?)/(\S+?);base64,`)

	// 根据文件类型选择路径和正则表达式
	switch file {
	case 1:
		path = "avatar/"
	case 2:
		path = "cover/"
	case 3:
		path = "music/"
	case 4:
		path = "video/"
	case 5:
		path = "images/"
	case 6:
		path = "dynamic_image/"
	case 7:
		path = "audio/"
	case 8:
		path = "avatar/"
	default:
		return "", "", fmt.Errorf("invalid file type")
	}

	// 使用正则表达式提取 MIME 类型
	matches := re.FindStringSubmatch(base64Data)
	if len(matches) < 2 {
		return "", "", fmt.Errorf("invalid base64 data format")
	}

	mimeType := matches[2]
	// 将 MIME 类型转换为小写，确保后缀统一
	mimeType = strings.ToLower(mimeType)

	// 返回文件路径和 MIME 类型
	return path, mimeType, nil
}
